<template>
  <div class="tinymce-box">
    <editor
      v-model="myValue"
      :init="init"
      :disabled="disabled"
      @onClick="onClick">
    </editor>
    <!-- <el-progress class="tinymce-upload-progress"  type="circle" v-show="percentage >0 && percentage<100" :percentage="percentage"></el-progress> -->
  </div>
</template>
<style >
.tox-tinymce-aux {
    z-index: 999999 !important;
}

.tinymce-upload-progress{
    position: fixed !important;
    text-align: center;
    top: 0;
    left: 0;
    /* top: 50%;
    left: 50%;
    transform: translate(-50%, -50%); */
    z-index: 999999999 !important;
  }
</style>
<script>
// 文档 http://tinymce.ax-z.cn/
// 引入组件
import tinymce from 'tinymce/tinymce' // tinymce默认hidden，不引入不显示
import Editor from '@tinymce/tinymce-vue'

// 引入富文本编辑器主题的js和css
import 'tinymce/skins/content/default/content.css'
import 'tinymce/models/dom'
import 'tinymce/themes/silver'
import 'tinymce/icons/default/icons' // 解决了icons.js 报错Unexpected token '<'

// 编辑器插件plugins
// 更多插件参考：https://www.tiny.cloud/docs/plugins/
import 'tinymce/plugins/image'// 插入上传图片插件
import 'tinymce/plugins/media'// 插入视频插件
import 'tinymce/plugins/table'// 插入表格插件
import 'tinymce/plugins/lists'// 列表插件
import 'tinymce/plugins/wordcount'// 字数统计插件
import 'tinymce/plugins/link'
import 'tinymce/plugins/code'
import 'tinymce/plugins/preview'
import 'tinymce/plugins/fullscreen'
import 'tinymce/plugins/help'
export default {
  components: {
    Editor
  },
  name: 'Tinymce',
  props: {
    // 默认的富文本内容
    value: {
      type: String,
      default: ''
    },
    // 基本路径，默认为空根目录，如果你的项目发布后的地址为目录形式，
    // 即abc.com/tinymce，baseUrl需要配置成tinymce，不然发布后资源会找不到
    baseUrl: {
      type: String,
      default: window.location.origin ? window.location.origin : ''
    },
    // 禁用
    disabled: {
      type: Boolean,
      default: false
    },
    plugins: {
      type: [String, Array],
      default: 'link lists image code table wordcount media preview fullscreen help fontsizeselect'
    },
    toolbar: {
      type: [String, Array],
      default: 'bold  image media italic underline strikethrough fontsizeselect fontselect | formatselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent blockquote | undo redo | link unlink code lists table image media | removeformat | fullscreen preview'
    }
  },
  data () {
    return {
      percentage:0,
      init: {
        language_url: `./tinymce/langs/zh-Hans.js`,
        language: 'zh-Hans',
        skin_url: `./tinymce/skins/ui/oxide`,
        fontsize_formats: "14px 16px 18px 20px 24px 26px 28px 30px 32px 36px", //字体大小
        font_formats:"微软雅黑=Microsoft YaHei,Helvetica Neue;PingFang SC;sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun;serifsans-serif;Terminal=terminal;monaco;Times New Roman=times new roman;times", //字体
        // skin_url: 'tinymce/skins/ui/oxide-dark', // 暗色系
        convert_urls: false,
        height: 650,
        // content_css（为编辑区指定css文件）,加上就不显示字数统计了
        content_css: `./tinymce/skins/content/default/content.css`,
        // （指定需加载的插件）
        plugins: this.plugins,
        toolbar: this.toolbar, // （自定义工具栏）
        file_picker_types : 'media',
        file_picker_callback:(cb, value, meta)=>{ 
                 let that = this;
              //创建一个隐藏的type=file的文件选择input
                    let input = document.createElement('input');
                    let filetype = meta.filetype;
                    input.setAttribute('type', 'file');
                    input.setAttribute('accept', 'video/*');
                    input.onchange = function(){
                      let file = this.files[0];
                      var xhr, formData;
                      xhr = new XMLHttpRequest();
                      xhr.open('POST', process.env.VUE_APP_BASE_API + '/editor/upload',);
                      xhr.withCredentials = self.credentials;
                      xhr.upload.onprogress = function (e) {
                        that.percentage = Math.floor(e.loaded / e.total * 100);
                      };
                      xhr.onerror = function () {
                        //根据自己的需要添加代码
                        return;
                      };
                      xhr.onload = function () {
                        let json;
                        if (xhr.status < 200 || xhr.status >= 300) {
                          console.log('HTTP 错误: ' + xhr.status);
                          return;
                        }
                        json = JSON.parse(xhr.responseText);
                   
                        //假设接口返回JSON数据为{status: 0, msg: "上传成功", data: {location: "/localImgs/1546434503854.mp4"}}
                        if(json.code==200){
                          //接口返回的文件保存地址
                          let mediaLocation=json.location;
                          //cb()回调函数，将mediaLocation显示在弹框输入框中
                          cb(mediaLocation, { title: file.name });
                        }else{
                          //  that.$notify.error({
                          //   title: '错误',
                          //   message: '这是一条错误的提示消息'
                          // });
                          that.$message.error(json.msg);return;
                          
                        }
                        
                      };
                      formData = new FormData();
                      //假设接口接收参数为file,值为选中的文件
                      formData.append('file', file);
                      //正式使用将下面被注释的内容恢复
                      xhr.send(formData);
                    }
                    //触发点击
                    input.click();
        
                
        },
        statusbar: false, // 底部的状态栏
        menubar: 'file edit insert view format table tools', // （1级菜单）最上方的菜单
        branding: false, // （隐藏右下角技术支持）水印“Powered by TinyMCE”
        menu : { 
        file : {title : 'File' , items : 'newdocument'}, 
        edit : {title : 'Edit' , items : 'undo redo | cut copy paste pastetext | selectall'}, 
        insert : {title : 'Insert', items : 'link media | template hr'}, 
        view : {title : 'View' , items : 'visualaid'}, 
        format : {title : 'Format', items : 'bold italic underline strikethrough superscript subscript fontsizeselect  | formats | removeformat'}, 
        table : {title : 'Table' , items : 'inserttable tableprops deletetable | cell row column'}, 
        tools : {title : 'Tools' , items : 'spellchecker code'},
        }, 
        images_upload_url:process.env.VUE_APP_BASE_API + '/editor/upload',
        // 此处为图片上传处理函数，这个直接用了base64的图片形式上传图片，
        // 如需ajax上传可参考https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_handler
        // images_upload_handler: (blobInfo, success, failure) => {
        //   const img = 'data:image/jpeg;base64,' + blobInfo.base64()
        //   success(img)
        //   console.log(failure)
        // }
      },
      myValue: this.value,
    }
  },
  mounted () {
// setInterval(() => {this.$message.error("dwaddddwdaddddd");return;}, 2000)
      tinymce.init({})
  },
  methods: {
    // 添加相关的事件，可用的事件参照文档=> https://github.com/tinymce/tinymce-vue => All available events
    // 需要什么事件可以自己增加
    onClick(e) {
      console.log('handleClick')
      this.$emit('onClick', e, tinymce)
    },
    // 可以添加一些自己的自定义事件，如清空内容
    clear () {
      this.myValue = "";
    },
  },
  watch: {
    value(newValue) {
      this.myValue = newValue;
    },
    myValue(newValue) {
      this.$emit("input", newValue);
    }
  }
}

</script>
<style scoped>

</style>


